package com.sfac.springBoot.module.test.service.Impl;

import com.sfac.springBoot.module.common.vo.Result;
import com.sfac.springBoot.module.common.vo.Search;
import com.sfac.springBoot.module.test.dao.StudentDao;
import com.sfac.springBoot.module.test.pojo.Student;
import com.sfac.springBoot.module.test.service.StudentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * personal demo
 **/

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;
    @Override
    @Transactional
    public Result<Student> insertStudent(Student student) {
        studentDao.saveAndFlush(student);
        return new Result<>(Result.ResultStatus.SUCCESS.code,"success",student);
    }

    @Override
    @Transactional
    public Result<Student> updateStudent(Student student) {
        studentDao.saveAndFlush(student);
        return new Result<>(Result.ResultStatus.SUCCESS.code,"success",student);
    }

    @Override
    @Transactional
    public Result<Object> deleteStudentById(Integer id) {
        studentDao.deleteById(id);
        return new Result<>(Result.ResultStatus.SUCCESS.code,"delete success");
    }

    @Override
    @Transactional
    public Student getStuById(int id) {
        return studentDao.getById(id);

    }

    @Override
    @Transactional
    public Page<Student> getStuBySearch(Search search) {
        search.init();

        Sort.Direction direction= StringUtils.isBlank(search.getDirection())
                ||search.getDirection().toLowerCase().equals("asc")? Sort.Direction.ASC:
                Sort.Direction.DESC;
        String order=StringUtils.isBlank(search.getSort())?"id":search.getSort();
        Sort sort= Sort.by(direction,order);
        Pageable pageable= PageRequest.of(search.getCurrentPage()-1,
                search.getPageSize(),sort);

        Student student = new Student();
        student.setName(search.getKeyword());
        ExampleMatcher matcher=ExampleMatcher.matchingAny().
                withMatcher("name",match->match.contains() )
                .withIgnorePaths("id","age");
        Example<Student> example=Example.of(student,matcher);
        return studentDao.findAll(example,pageable);
    }


}
